"""
协议编解码异常定义
建立清晰的异常层次结构
"""
from typing import List, Optional, Any


class ProtocolError(Exception):
    """协议处理基础异常"""

    def __init__(self, message: str, path: Optional[List[str]] = None,
                 details: Optional[dict] = None):
        self.message = message
        self.path = path or []
        self.details = details or {}
        super().__init__(self.format_message())

    def format_message(self) -> str:
        """格式化错误消息"""
        path_str = '/'.join(self.path) if self.path else 'root'
        msg = f"[{path_str}] {self.message}"

        if self.details:
            details_str = ', '.join(f"{k}={v}" for k, v in self.details.items())
            msg += f" ({details_str})"

        return msg


class EncodeError(ProtocolError):
    """编码错误"""
    pass


class DecodeError(ProtocolError):
    """解码错误"""
    pass


class ValidationError(ProtocolError):
    """验证错误"""
    pass


class ConfigError(ProtocolError):
    """配置错误"""
    pass


# 具体错误类型

class FieldNotFoundError(EncodeError):
    """字段不存在错误"""
    pass


class ValueOutOfRangeError(EncodeError):
    """数值越界错误"""

    def __init__(self, path: List[str], value: Any, min_val: int, max_val: int):
        super().__init__(
            f"数值越界: {value} 不在范围 [{min_val}, {max_val}] 内",
            path,
            {'value': value, 'min': min_val, 'max': max_val}
        )


class BufferOverflowError(DecodeError):
    """缓冲区溢出错误"""

    def __init__(self, path: List[str], required: int, available: int):
        super().__init__(
            f"缓冲区不足: 需要{required}字节,仅有{available}字节",
            path,
            {'required': required, 'available': available}
        )


class UnsupportedTypeError(ProtocolError):
    """不支持的类型错误"""

    def __init__(self, path: List[str], type_name: str):
        super().__init__(
            f"不支持的类型: {type_name}",
            path,
            {'type': type_name}
        )


class ConditionalFieldError(ProtocolError):
    """条件字段错误"""

    def __init__(self, path: List[str], condition: str, reason: str):
        super().__init__(
            f"条件表达式错误: {condition} - {reason}",
            path,
            {'condition': condition}
        )


class LengthMismatchError(ProtocolError):
    """长度不匹配错误"""

    def __init__(self, path: List[str], expected: int, actual: int):
        super().__init__(
            f"长度不匹配: 期望{expected}字节,实际{actual}字节",
            path,
            {'expected': expected, 'actual': actual}
        )


class ChecksumError(DecodeError):
    """校验和错误"""

    def __init__(self, expected: int, actual: int):
        super().__init__(
            f"校验和错误: 期望0x{expected:02x},实际0x{actual:02x}",
            [],
            {'expected': expected, 'actual': actual}
        )
